// API工具类
import axios from 'axios';

// 获取后端API地址，优先从localStorage获取，便于在其他电脑测试时修改
const getApiBaseUrl = () => {
  // 优先从localStorage获取，如果没有则使用默认值（本机地址）
  return localStorage.getItem('apiBaseUrl') || 'http://127.0.0.1:3000';
};

// 创建axios实例
const http = axios.create({
  baseURL: getApiBaseUrl(),
  timeout: 10000
});

// 请求拦截器
http.interceptors.request.use(
  config => {
    // 添加token到请求头
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    console.error('API请求错误:', error);
    return Promise.reject(error.response?.data || error);
  }
);

/**
 * API工具类
 * 封装所有API请求方法
 */
class ApiService {
  // 修改后端API地址，便于在其他电脑上测试
  static setApiBaseUrl(url) {
    localStorage.setItem('apiBaseUrl', url);
    http.defaults.baseURL = url;
    console.log('API地址已切换为:', url);
    return true;
  }
  
  // 获取当前配置的API地址
  static getApiBaseUrl() {
    return http.defaults.baseURL;
  }
  
  // 用户相关API
  static async login(formData) {
    const { username, password, role } = formData;
    // 直接返回响应，因为响应拦截器已经处理了data字段
    return await http.post('/api/users/login', { username, password, role });
  }

  static async updatePassword(data) {
    return await http.post('/api/users/change-password', data);
  }
  
  /**
   * 重置学生密码
   * @param {string} studentId - 学生ID
   */
  static async resetPassword(studentId) {
    return await http.post(`/api/users/${studentId}/reset-password`);
  }
  
  /**
   * 获取学生作业提交列表
   */
  static async getStudentSubmissions() {
    return await http.get('/api/submissions/student');
  }
  
  /**
   * 获取可提交的作业列表
   */
  static async getAvailableHomeworks() {
    return await http.get('/api/homeworks/available');
  }
  
  /**
   * 获取作业列表
   */
  static async getHomeworks() {
    return await http.get('/api/homeworks');
  }
  
  /**
   * 创建作业（发布作业）
   */
  static async createHomework(formData) {
    return await http.post('/api/homeworks', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
  
  /**
   * 更新作业评分
   */
  static async updateSubmissionScore(submissionId, data) {
    return await http.put(`/api/submissions/${submissionId}/grade`, data);
  }
  
  /**
   * 退回作业
   */
  static async rejectSubmission(submissionId, data) {
    return await http.put(`/api/submissions/${submissionId}/reject`, data);
  }
  
  /**
   * 评分作业（兼容性方法）
   */
  static async gradeSubmission(submissionId, data) {
    return await this.updateSubmissionScore(submissionId, data);
  }
  
  /**
   * 提交作业
   */
  static async submitHomework(formData) {
    return await http.post('/api/submissions', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
  
  /**
   * 获取作业提交列表（教师使用）
   */
  static async getSubmissions(filters = {}) {
    return await http.get('/api/submissions', { params: filters });
  }
  
  /**
   * 获取年级排名
   * @param {string} grade - 年级，默认值为'1'
   */
  static async getGradeRankings(grade = '1') {
    return await http.get('/api/submissions/rankings/grade', { params: { grade } });
  }
  
  /**
   * 获取班级排名
   */
  static async getClassRankings(classId) {
    return await http.get(`/api/submissions/rankings/class/${classId}`);
  }

  static async getUserInfo() {
    return await http.get('/api/users/info');
  }

  static async registerStudent(data) {
    // 兼容两种调用方式：
    // 1. 直接传入对象：registerStudent({username, password, class_id, role})
    // 2. 传入分散参数：registerStudent(username, password, classId)
    
    // 如果是对象参数格式（从StudentManagement.vue传入的）
    if (typeof data === 'object' && data !== null) {
      const { username, password, class_id, role, name } = data;
      return await http.post('/api/users/register', { 
        username, 
        password, 
        role: role || 'student', 
        classId: class_id,
        name  // 传递学生姓名
      });
    }
    
    // 原有的参数格式（为保持向后兼容）
    const [username, password, classId] = arguments;
    return await http.post('/api/users/register', { username, password, role: 'student', classId });
  }

  static async deleteUser(userId) {
    return await http.delete(`/api/users/${userId}`);
  }

  /**
   * 获取学生列表（支持分页）
   * @param {Object} filters - 过滤条件，包含class_id和search
   * @param {number} page - 当前页码
   * @param {number} pageSize - 每页数量
   */
  static async getStudents(filters = {}, page = 1, pageSize = 10) {
    return await http.get('/api/users/students', {
      params: {
        ...filters,
        page,
        pageSize
      }
    });
  }
  
  /**
   * 获取指定班级的学生列表
   * @param {string} classId - 班级ID
   */
  static async getClassStudents(classId) {
    // 使用getStudents方法并传入class_id参数进行过滤
    // 设置pageSize为1000获取所有学生，不进行分页限制
    return await this.getStudents({ class_id: classId }, 1, 1000);
  }

  /**
   * 获取班级列表（支持分页）
   * @param {Object} params - 请求参数
   * @param {number} [params.page=1] - 页码
   * @param {number} [params.pageSize=10] - 每页数量
   * @returns {Promise} 班级列表数据
   */
  static async getClasses(params = {}) {
    const { page = 1, pageSize = 10 } = params;
    return await http.get('/api/classes', { params: { page, pageSize } });
  }

  static async getClassById(classId) {
    return await http.get(`/api/classes/${classId}`);
  }

  static async createClass(data) {
    // 适配ClassManagement.vue中的调用方式，支持传入对象参数
    const className = data.name || data.className;
    const grade = data.grade || '1'; // 默认年级为1
    return await http.post('/api/classes', { className, grade });
  }

  static async updateClass(classId, data) {
    // 适配ClassManagement.vue中的调用方式，支持传入对象参数
    const className = data.name || data.className;
    const grade = data.grade || '1'; // 默认年级为1
    return await http.put(`/api/classes/${classId}`, { className, grade });
  }

  static async deleteClass(classId) {
    return await http.delete(`/api/classes/${classId}`);
  }

  // 作业相关API
  static async getAssignments(classId = null) {
    const params = classId ? { classId } : {};
    return await http.get('/api/homeworks', { params });
  }

  static async getAssignmentById(assignmentId) {
    return await http.get(`/api/homeworks/${assignmentId}`);
  }

  static async createAssignment(classId, title, content) {
    // 创建FormData对象，适配后端singleFileUpload中间件
    const formData = new FormData();
    formData.append('classId', classId);
    formData.append('title', title);
    formData.append('content', content);
    return await http.post('/api/homeworks', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }

  static async updateAssignment(assignmentId, title, content, file = null, classId = null, deadline = null, images = null) {
    // 创建FormData对象，适配后端singleFileUpload中间件
    const formData = new FormData();
    formData.append('title', title);
    formData.append('content', content);
    if (classId) formData.append('classId', classId);
    if (deadline) formData.append('deadline', deadline);
    if (images) formData.append('images', images);
    if (file) formData.append('attachment', file);
    return await http.put(`/api/homeworks/${assignmentId}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }

  static async deleteAssignment(assignmentId) {
    return await http.delete(`/api/homeworks/${assignmentId}`);
  }

  // 作业提交相关API
  // 注意：getSubmissions方法已在文件上方定义，此方法被移除以避免冲突

  static async getSubmissionById(submissionId) {
    return await http.get(`/api/submissions/${submissionId}`);
  }

  static async createSubmission(assignmentId, content, files = []) {
    const formData = new FormData();
    formData.append('assignmentId', assignmentId);
    formData.append('content', content);
    files.forEach(file => {
      formData.append('files', file);
    });
    return await http.post('/api/submissions', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }

  static async gradeSubmission(submissionId, gradeForm) {
    return await http.put(`/api/submissions/${submissionId}/grade`, gradeForm);
  }

  // 排名相关API
  static async getSchoolRank() {
    return await http.get('/api/rankings/school');
  }

  static async getClassRank(classId) {
    return await http.get(`/api/submissions/rankings/class/${classId}`);
  }

  static async getStudentRank(studentId) {
    return await http.get(`/api/rankings/student/${studentId}`);
  }
}

// 创建API实例并导出
export const api = {
  // 用户相关
  login: ApiService.login,
  changePassword: ApiService.changePassword,
  getUserInfo: ApiService.getUserInfo,
  registerStudent: ApiService.registerStudent,
  deleteUser: ApiService.deleteUser,
  updatePassword: ApiService.updatePassword,
  resetPassword: ApiService.resetPassword,
  getStudents: ApiService.getStudents,
  // 创建用户（用于新增学生）
  createUser: ApiService.registerStudent,
  // 更新用户信息（临时实现，需要后端支持）
  updateUser: async function(userId, data) {
    // 目前后端没有专门的updateUser API，这里返回一个模拟成功的响应
    // 实际应用中需要后端提供更新用户信息的API
    console.log('更新用户信息:', userId, data);
    return { success: true, message: '用户信息已更新' };
  },
  
  // 班级相关
  getClasses: ApiService.getClasses,
  getClassById: ApiService.getClassById,
  createClass: ApiService.createClass,
  updateClass: ApiService.updateClass,
  deleteClass: ApiService.deleteClass,
  
  // 作业相关
  getAssignments: ApiService.getAssignments,
  getAssignmentById: ApiService.getAssignmentById,
  createAssignment: ApiService.createAssignment,
  updateAssignment: ApiService.updateAssignment,
  deleteAssignment: ApiService.deleteAssignment,
  
  // 作业提交相关
  getSubmissions: ApiService.getSubmissions,
  getSubmissionById: ApiService.getSubmissionById,
  createSubmission: ApiService.createSubmission,
  gradeSubmission: ApiService.gradeSubmission,
  getStudentSubmissions: ApiService.getStudentSubmissions,
  getAvailableHomeworks: ApiService.getAvailableHomeworks,
  submitHomework: ApiService.submitHomework,
  getHomeworks: ApiService.getHomeworks,
  createHomework: ApiService.createHomework,
  updateSubmissionScore: ApiService.updateSubmissionScore,
  rejectSubmission: ApiService.rejectSubmission,
  
  // 排名相关
  getSchoolRank: ApiService.getSchoolRank,
  getClassRank: ApiService.getClassRank,
  getStudentRank: ApiService.getStudentRank,
  getGradeRankings: ApiService.getGradeRankings,
  getClassRankings: ApiService.getClassRankings,
  
  // 学生相关
  getStudents: ApiService.getStudents,
  getClassStudents: ApiService.getClassStudents
};